package cn.stacey.spring.ssm.aspect;

import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import cn.stacey.spring.ssm.exception.ServiceException;

@ControllerAdvice
public class DefaultExceptionHandler {
	//记录日志
	private Logger logger=LoggerFactory.getLogger(DefaultExceptionHandler.class);
	@ExceptionHandler(DataIntegrityViolationException.class)
	public String handleException(DataIntegrityViolationException e,Model model) {
		System.out.println("捕获到数据完整性异常"+e.getMessage());
		model.addAttribute("errorCode",20001);
		model.addAttribute("errorMessage","服务器内部出错，请稍后重试");
		//记录日志
		logger.error("数据库访问异常",e);
		//调试信息
		
		return "/error/500";
	}
	
	/**
	 *处理service异常
	 */
	@ExceptionHandler(ServiceException.class)
	public String handleServiceException(ServiceException e,Model model) {
		
		model.addAttribute("errorCode",e.getCode());
		model.addAttribute("errorMessage",e.getMessage());
		//记录日志
		logger.error("service异常",e);
		//调试信息
		
		return "/error/500";
	}
	
	//处理文件上传异常
	@ExceptionHandler(MaxUploadSizeExceededException.class)
	public String handleFileUploadException(MaxUploadSizeExceededException e,Model model) {
		
		model.addAttribute("errorCode",20003);
		model.addAttribute("errorMessage","文件大小超过了限制,最大允许大小为:"+e.getMaxUploadSize());
		//记录日志
		logger.error("service异常",e);
		//调试信息
		
		return "/error/500";
	}
	
	@ExceptionHandler(Exception.class)
	public String handlerGeneralException(Exception e) {
		logger.error("未知的服务器异常");
		return "/error/500";
		
	}
	
}
